import React, { useEffect, useState } from "react";
import { Swiper, Toast } from "antd-mobile";
import { useSearchParams } from "react-router-dom";

import Barrage from "../../components/pages/Video/VideoBarrage";
import { videoService, collectionService, handleApiResponse, handleApiError } from "../../utils/api";
import type { VideoCollectionItem } from "../../type";
import "./index.css";
import TopNav from '../../components/topNav'
import common_button_collection_large_n from '../../assets/icon/common_button_collection_large_n.png'
import common_button_collection_large_s from '../../assets/icon/common_button_collection_large_s.png'
import common_icon_comment_large_n from '../../assets/icon/common_icon_comment_large_n.png'
// 视频项类型定义
interface VideoItem {
  id: number;
  categoryId: number;
  title: string;
  originalUrl: string;
  shearUrl: string;
  abstracts: string;
  thumbnail: string;
  duration: number;
  price: number;
  whetherBuy: number;
  whetherCollection: number; // 1=已收藏, 2=未收藏
  buyNum: number;
  createTime: number;
}

// 视频列表请求参数
interface VideoListParams {
  categoryId: number;
  page: number;
  count: number;
}

const CvideoPage: React.FC = () => {
  const [searchParams] = useSearchParams();
  const [videoList, setVideoList] = useState<VideoItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [currentVideoIndex, setCurrentVideoIndex] = useState<number>(0);
  const [collectionLoading, setCollectionLoading] = useState<boolean>(false);
  const [showCommentModal, setShowCommentModal] = useState<boolean>(false);
  const [commentContent, setCommentContent] = useState<string>('');
  const [commentLoading, setCommentLoading] = useState<boolean>(false);

  // 生成随机整数
  const getRandomInt = (min: number, max: number): number => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  };

  // 获取视频列表
  const getVideoList = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const videoId = searchParams.get('videoId');
      
      if (videoId) {
        // 如果传递了特定的videoId，从收藏列表中获取该视频
        // 这里应该调用获取收藏视频列表的API，然后找到对应的视频
        const response = await collectionService.getVideoCollectionList({
          page: 1,
          count: 100 // 获取更多数据以确保能找到目标视频
        });
        const collectionData = handleApiResponse<VideoCollectionItem[]>(response);
        
        // 查找指定的视频
        const targetVideo = collectionData.find(item => item.videoId === parseInt(videoId));
        
        if (targetVideo) {
          // 将收藏的视频转换为VideoItem格式并显示
          const videoItem: VideoItem = {
            id: targetVideo.videoId,
            categoryId: 1, // 收藏列表中没有categoryId，使用默认值
            title: targetVideo.title,
            originalUrl: targetVideo.original || targetVideo.shearUrl || '',
            shearUrl: targetVideo.shearUrl || '',
            abstracts: '', // 收藏列表中没有abstracts，使用空字符串
            thumbnail: '', // 收藏列表中没有thumbnail，使用空字符串
            duration: targetVideo.duration,
            price: targetVideo.price,
            whetherBuy: targetVideo.whetherBuy || 2,
            whetherCollection: 1, // 从收藏列表来的，肯定是已收藏
            buyNum: targetVideo.buyNum || 0,
            createTime: targetVideo.createTime
          };
          setVideoList([videoItem]);
          setCurrentVideoIndex(0);
        } else {
          // 如果没找到，显示错误信息
          setError('未找到该视频');
        }
      } else {
        // 没有指定videoId，正常获取随机视频列表
        const params: VideoListParams = {
          categoryId: getRandomInt(1, 6),
          page: 1,
          count: 8,
        };

        const response = await videoService.getVideoList(params);
        const data = handleApiResponse<VideoItem[]>(response);
        setVideoList(data);
      }
    } catch (err) {
      const errorMsg = handleApiError(err);
      setError(errorMsg);
      console.error('获取视频列表失败:', errorMsg);
    } finally {
      setLoading(false);
    }
  };

  // 处理视频切换
  const handleVideoChange = (index: number) => {
    setCurrentVideoIndex(index);
    console.log('切换到第', index + 1, '个视频');
  };

  // 处理收藏操作
  const handleCollection = async (videoId: number) => {
    if (collectionLoading) return; // 防止重复点击
    
    try {
      setCollectionLoading(true);
      const currentVideo = videoList[currentVideoIndex];
      if (!currentVideo) return;

      const isCurrentlyCollected = currentVideo.whetherCollection === 1;
      
      // 调用相应的API
      if (isCurrentlyCollected) {
        // 取消收藏
        await videoService.cancelVideoCollection(videoId);
        Toast.show('取消收藏成功');
      } else {
        // 添加收藏
        await videoService.addVideoCollection(videoId);
        Toast.show('收藏成功');
      }

      // 只有在API调用成功后才更新本地状态
      const updatedVideoList = videoList.map((video, index) => {
        if (index === currentVideoIndex) {
          return {
            ...video,
            whetherCollection: video.whetherCollection === 1 ? 2 : 1
          };
        }
        return video;
      });
      setVideoList(updatedVideoList);
      
    } catch (err) {
      const errorMsg = handleApiError(err);
      Toast.show(errorMsg);
      console.error('收藏操作失败:', errorMsg);
      // 注意：这里不更新本地状态，保持原有状态
    } finally {
      setCollectionLoading(false);
    }
  };

  // 处理评论操作
  const handleComment = (videoId: number) => {
    setShowCommentModal(true);
    setCommentContent('');
  };

  // 处理评论发表
  const handleSubmitComment = async () => {
    if (!commentContent.trim()) {
      Toast.show('请输入评论内容');
      return;
    }

    if (commentLoading) return;

    try {
      setCommentLoading(true);
      const currentVideo = videoList[currentVideoIndex];
      if (!currentVideo) return;

      await videoService.addVideoComment(currentVideo.id, commentContent.trim());
      Toast.show('评论发表成功');
      
      // 清空输入框并关闭弹窗
      setCommentContent('');
      setShowCommentModal(false);
      
    } catch (err) {
      const errorMsg = handleApiError(err);
      Toast.show(errorMsg);
      console.error('评论发表失败:', errorMsg);
    } finally {
      setCommentLoading(false);
    }
  };

  // 关闭评论弹窗
  const handleCloseCommentModal = () => {
    setShowCommentModal(false);
    setCommentContent('');
  };

  // 初始化数据
  useEffect(() => {
    getVideoList();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <div className="videoBox">
      <div style={{position:'fixed',top:0,left:0,right:0,zIndex:100}}>
      <TopNav/>
      </div>
      {loading ? (
        <div className="loading-state">
          加载中...
        </div>
      ) : error ? (
        <div className="error-state">
          {error}
        </div>
      ) : videoList.length > 0 ? (
        <Swiper
          indicator={() => null}
          direction="vertical"
          style={{ width: "100vw", height: "100vh" }}
          onIndexChange={handleVideoChange}
        >
          {videoList.map((item: VideoItem, index: number) => (
            <Swiper.Item key={item.id}>
              <Barrage />
              <video 
                controls 
                height="100%" 
                width="100%"
                poster={item.thumbnail}
                preload="metadata"
              >
                <source src={item.originalUrl} type="video/mp4" />
                您的浏览器不支持视频播放
              </video>
              
              {/* 右侧操作按钮区域 */}
              <div className="video-actions">
                <div 
                  className={`action-item ${collectionLoading ? 'loading' : ''}`} 
                  onClick={() => handleCollection(item.id)}
                >
                  <img 
                    src={item.whetherCollection === 1 ? common_button_collection_large_s : common_button_collection_large_n}
                    alt="收藏"
                    className="action-icon"
                  />
                </div>
                <div className="action-item" onClick={() => handleComment(item.id)}>
                  <img 
                    src={common_icon_comment_large_n}
                    alt="评论"
                    className="action-icon"
                  />
                </div>
              </div>
            </Swiper.Item>
          ))}
        </Swiper>
      ) : (
        <div className="empty-state">
          暂无视频数据
        </div>
      )}

      {/* 评论弹窗 */}
      {showCommentModal && (
        <div className="comment-modal-overlay" onClick={handleCloseCommentModal}>
          <div className="comment-modal" onClick={(e) => e.stopPropagation()}>
            <div className="comment-modal-header">
              <h3>发表评论</h3>
              <button className="close-btn" onClick={handleCloseCommentModal}>×</button>
            </div>
            <div className="comment-modal-body">
              <textarea
                className="comment-input"
                placeholder="请输入您的评论内容..."
                value={commentContent}
                onChange={(e) => setCommentContent(e.target.value)}
                maxLength={200}
                rows={4}
              />
              <div className="comment-counter">
                {commentContent.length}/200
              </div>
            </div>
            <div className="comment-modal-footer">
              <button 
                className="cancel-btn" 
                onClick={handleCloseCommentModal}
                disabled={commentLoading}
              >
                取消
              </button>
              <button 
                className={`submit-btn ${commentLoading ? 'loading' : ''}`}
                onClick={handleSubmitComment}
                disabled={commentLoading || !commentContent.trim()}
              >
                {commentLoading ? '发表中...' : '发表'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default CvideoPage;
